<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace app\shop\api;
use app\admin\api\DatatreeApi;
use app\common\api\BaseApi;
use app\shop\api\ProductAttrApi;
use app\shop\api\ProductImageApi;
use app\shop\api\ProductSkuApi;

use app\shop\model\ProductAttr;
use app\shop\model\ProductGroup;
use app\shop\model\ProductImage;
use app\shop\model\Product;
use app\shop\model\ProductProp;
use app\extend\Page;

class ProductApi extends BaseApi{
    /**
     *
     * 查询商品包含的所有国家信息
     */
    const QUERY_ALL_COUNTRY = "shop/ProductApi/queryAllCountry";

    /**
     *
     * 查询商品信息根据用户ID
     */
    const QUERY_WITH_STORE_UID = "shop/ProductApi/queryWithStoreUID";
    /**
     * 查询商品信息根据分组
     */
    const QUERY_BY_GROUP = "shop/ProductApi/queryByGroup";
    /**
     * 查询商品信息并包含店铺信息
     */
    const QUERY_WITH_STORE = "shop/ProductApi/queryWithStore";
    //查询具体规格商品信息
    const GET_WITH_SKU = "shop/ProductApi/getWithSku";

    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "shop/ProductApi/queryNoPaging";
    /**
     * 查询 不分页 已上架 未删除
     */
    const QUERY_NO_PAGING_ON_SHELF = "shop/ProductApi/queryNoPagingOnShelf";
    /**
     * 查询 已上架 未删除
     */
    const QUERY_ON_SHELF = "shop/ProductApi/queryOnShelf";
    /**
     * 添加
     */
    const ADD = "shop/ProductApi/add";
    const OLD_ADD = "shop/ProductApi/oldAdd";
    /**
     * 保存
     */
    const SAVE = "shop/ProductApi/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "shop/ProductApi/saveByID";

    /**
     * 删除
     */
    const DELETE = "shop/ProductApi/delete";
    /**
     * 删除
     */
    const PRETEND_DELETE = "shop/ProductApi/pretendDelete";

    /**
     * 查询
     */
    const QUERY = "shop/ProductApi/query";
    /**
     * 查询一条数据
     */
    const GET_INFO = "shop/ProductApi/getInfo";

	const COUNT="shop/ProductApi/count";

    //减少库存
    const SET_DEC="shop/ProductApi/setDec";
    //增加库存
    const SET_INC="shop/ProductApi/setInc";

    const QUERY_WITH_COUNT = "shop/ProductApi/queryWithCount";
    const QUERY_MMZ_COUNT = "shop/ProductApi/queryMmzCount";

    /**
     * 获取商品详情信息
     */
    const DETAIL="shop/ProductApi/detail";
    const DETAIL_GIFT="shop/ProductApi/detailGift";
    /**
     * 获取商品信息，随机10条
     */
    const RANDOM_QUERY="shop/ProductApi/randomQuery";
    /**
     * 批量上下架
     */
    const SHELF_ALL = "shop/ProductApi/shelfAll";

    protected function _init(){
		$this->model = new Product();
	}

    public function getWithSku($pid,$psku_id,$uid=0,$group_id=0){
        $pid      = intval($pid);
        $psku_id  = intval($psku_id);
        $uid      = intval($uid);
        $group_id = intval($group_id);
        $r        = apiCall(ProductApi::GET_INFO,[['id' => $pid]]);
        if(!$r['status']) return $this->apiReturnErr($r['info']);
        $info = $r['info'];
        //查询会员价
        $r = apiCall(ProductSkuApi::GET_INFO_BY_USER,[$uid,$psku_id]);
        if(!$r['status']) return $this -> apiReturnErr($r['info']);
        if(!empty($r['info']) && $r['info']['product_id'] == $pid){
            $info['sku_id']    = $r['info']['sku_id'];
            $info['sku_desc']  = $r['info']['sku_desc'];
            $info['price']     = $r['info']['price'];
            $info['ori_price'] = $r['info']['ori_price'];
            $info['icon_url']  = $r['info']['icon_url'];
        }else{
            return $this -> apiReturnErr("商品规格有误");
        }
        //查询该规格活动价-验证分组
        if($group_id){
            $r = apiCall(ProductGroupApi::GET_INFO,[['p_id'=>$pid,'g_id'=>$group_id,'sku_id'=>$psku_id]]);
            if(!$r['status']) return $this->apiReturnErr($r['info']);
            if(!empty($r['info'])){
                if($r['info']['end_time']<time() || $r['info']['start_time']>time())
                return $this->apiReturnErr('分组未生效');
                if(floatval($r['info']['price'])>0) $info['price'] = $r['info']['price'];
            }
        }
        return $this->apiReturnSuc($info);
    }

    /**
     * add 添加
     * @param $entity
     * @return bool
     */
    public function oldAdd($entity) {
        $result = $this -> model -> create($entity, 1);
        // trace("---after createresult---");
        // trace($result);
        if (false === $result) {
            $error = $this -> model -> getError();
            return $this -> apiReturnErr($error);
        } else {
            // trace("---entity---");
            // trace($entity);
            //bug fix zhouzhou
            $result = $this -> model -> add();
            if ($result === false) {
                return $this -> apiReturnErr($this -> model -> getDbError());
            }
            return $this -> apiReturnSuc($result);
        }
    }
    public function shelfAll($onshelf,$ids){
        $this -> model -> startTrans();
        $error = false;
        foreach($ids as $k => $v){
            $map = ['id'=>$v];
            $entity = ['onshelf'=>$onshelf];
            $result = $this -> model -> create($entity, 2);
            if($result === false){
                $error = $this -> model -> getError();
            }
            $result = $this -> model -> where($map) -> save();
            if ($result === false) {
                $error = $this -> model -> getDbError();
            }
        }
        if($error === false){
            $this -> model -> commit();
            return $this -> apiReturnSuc("上架成功");
        }else{
            $this -> model -> rollback();
            return $this -> apiReturnErr($error);
        }
    }

    /**
     * query
     * @param 查询条件|null $map
     * @param array|分页参数 $page
     * @param bool|排序参数 $order
     * @param bool|点击分页时带参数 $params
     * @param bool $fields
     * @return array
     * @internal param 查询条件 $map
     * @internal param 分页参数 $page
     * @internal param 排序参数 $order
     * @internal param 点击分页时带参数 $params
     */
    public function query($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false) {
        $query = $this->model->alias('pro');

        $main_img_type = 6015;//主图
        $query = $query -> join('left join itboye_product_image as image where image.type='.$main_img_type.' on pro.id=image.pid');
        // $query = $query -> join('(select * from itboye_product_image where type='.$main_img_type.') as image on id=image.pid','left');

        if(!is_null($map)){
            $map['status'] = 1;
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();


        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
    }


    public function queryOnShelf($map = null,$page = array('curpage'=>0,'size'=>10),$order = false, $params = false, $fields = false){
        $query = $this -> model;

        $query = $query -> page($page['curpage'] . ',' . $page['size']);

        if($order !== false){
            $query = $query -> order($order);
        }
        if($fields !== false){
            $query = $query -> field($fields);
        }
        $map['status'] = 1;
        $map['onshelf'] = 1;
        $list = $query -> where($map) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();

        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("count" => $count,"show" => $show,"list" => $list));

    }

    public function queryNoPagingOnShelf($map = null,$order = false){
        $query = $this->model->alias('pro');

        $main_img_type = 6015;//主图

        $query = $query -> join('left join itboye_product_image as image on image.type='.$main_img_type.' and pro.id=image.pid');

        $map['status'] = 1;
        $map['onshelf'] = 1;

        $query = $query->where($map);

        if(!($order === false)){
            $query = $query -> order($order);
        }

        $result = $query -> select();

        if ($result === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        return $this -> apiReturnSuc($result);
    }

    /**
     * query
     * @param 查询条件|null $map
     * @param array|分页参数 $page
     * @param bool|排序参数 $order
     * @param bool|点击分页时带参数 $params
     * @param bool $fields
     * @return array
     * @internal param 查询条件 $map
     * @internal param 分页参数 $page
     * @internal param 排序参数 $order
     * @internal param 点击分页时带参数 $params
     */
    public function queryWithCount($map = null, $page = array('curpage'=>1,'size'=>10), $order = false, $params = false, $fields = false) {
        $pids_str = '';

        if($map && isset($map['service_ids']) && is_array($map['service_ids'])){
            $model = new \think\model();
            foreach ($map['service_ids'] as $v) {
                if($pids_str){
                   $r = $model ->query('select group_concat(p_id) as pids from itboye_product_service where dt_service_id ='.$v.' and p_id in ('.$pids_str.')');
                   if(false === $r) return $this->apiReturnErr($model->getDbError());
                    $pids_str = $r[0]['pids'];
                }else{
                   $r = $model ->query('select group_concat(p_id) as pids from itboye_product_service where dt_service_id ='.$v);
                   if(false === $r) return $this->apiReturnErr($model->getDbError());
                    $pids_str = $r[0]['pids'];
                }
            }
            unset($map['service_ids']);
            if($pids_str){
                if(isset($map['_string'])) $map['_string'].=' and `pro`.`id` in('.$pids_str.')';
                else $map['_string'] = '`pro`.`id` in ('.$pids_str.')';
            }
        }
        //itboye_product_image : img_id as img,pid
        //itboye_product_attr  : total_sales,buy_limit,is_second,view_cnt,pid as pro_id
        $main_img_type = 6015;//主图
        $query = $this -> model ->alias('pro')->
        join('left join itboye_product_image as image on image.type='.$main_img_type.' and pro.id=image.pid')
            -> join('(select min(price) as price,max(ori_price) as ori_price,product_id from itboye_product_sku group by product_id) as sku on id=sku.product_id','left')
            -> join('left join itboye_product_attr as attr on pro.id=attr.pid')
            ->join('(SELECT product_id as sku_pid,(`price` / `ori_price`) AS discount  FROM `itboye_product_sku` WHERE `ori_price` > 0 ORDER BY discount limit 1) as pc on pc.sku_pid = pro.id','left');
        // $query = $this -> model -> join('(select img_id as img,pid from itboye_product_image where type='.$main_img_type.') as image on id=image.pid','left') -> join('(select min(price) as price,max(ori_price) as ori_price,product_id from itboye_product_sku group by product_id) as sku on id=sku.product_id','inner') -> join('(select total_sales,buy_limit,is_second,view_cnt,pid as pro_id from itboye_product_attr ) a on id=a.pro_id','left');
        // trace($map['cate_id']);
        // if(isset($map['cate_id'])){
        //     $p = $map['cate_id'][1]; //bug
        //     unset($map['cate_id']);
        //     $map['cate_id'] = ['in',$p];
        // }
        if(!empty($map))      $query = $query->where($map);
        if(false !== $order)  $query = $query->order($order);
        if(false !== $fields) $query = $query->field($fields);
        $start = (intval($page['curpage'])-1)*intval($page['size']);
        $list = $query
        //->page($page['curpage'] . ',' . $page['size'])
        -> limit($start,$page['size'])
        -> select();

//        vendor_old('XSocketlog',APP_PATH.'index/vendor/XSocketlog','.class.php');
//        $s = new \socketlog('xiao');
//        $s->send($list);

        if (false === $list) return $this -> apiReturnErr($this -> model -> getDbError());
        //itboye_product_attr : is_second,pid as pro_id
        $count = $this -> model -> alias('pro')
          // -> join('(select img_id as img,pid from itboye_product_image where type='.$main_img_type.') as image on id=image.pid','left')
          -> join('(select min(price) as price,product_id from itboye_product_sku group by product_id) as sku on id=sku.product_id','inner')
          -> join('left join itboye_product_attr as attr on pro.id=attr.pid')
          -> where($map) -> count();

        // 分页跳转的时候保证查询条件
        // if (false !== $params) {
        //     foreach ($params as $key => $val) {
        //         $Page -> parameter[$key] = urlencode($val);
        //     }
        // }
        // $Page = new Page($count, $page['size']);
        // $show = $Page -> show();
        return $this -> apiReturnSuc(["count" => $count, "list" => $list]);
    }
    /**
     * query
     * @param 查询条件|null $map
     * @param array|分页参数 $page
     * @param bool|排序参数 $order
     * @param bool|点击分页时带参数 $params
     * @param bool $fields
     * @return array
     * @internal param 查询条件 $map
     * @internal param 分页参数 $page
     * @internal param 排序参数 $order
     * @internal param 点击分页时带参数 $params
     */
    public function queryMmzCount($map = null, $page = ['curpage'=>1,'size'=>10], $order = false, $params = false, $fields = false) {

        $main_img_type = 6015;//主图
        //product_image : img_id as main_img,pid
        //itboye_product_attr : is_second,view_cnt,pid as pro_id
        //common_member : uid as m_uid,nickname,head,sex
        //itboye_category : id as c_id,name as cate_name
        //itboye_mmz_winner_pepole : uid as win_uid,goods_id,win_time,evaluate_time,express_time
        $query = $this -> model ->alias('pro')-> join('left join itboye_product_image as image on pro.id=image.pid and image.type='.$main_img_type) -> join('left join itboye_product_attr as attr on pro.id=attr.pid') -> join('left join common_member as m on pro.uid=m.uid') -> join('left join itboye_category as c on pro.cate_id=c.id') -> join('left join itboye_mmz_winner_pepole as wp on pro.id=wp.goods_id');
        // trace($map['cate_id']);
        // if(isset($map['cate_id'])){
        //     $p = $map['cate_id'][1]; //bug
        //     unset($map['cate_id']);
        //     $map['cate_id'] = ['in',$p];
        // }
        if(!empty($map))      $query = $query->where($map);
        if(false !== $order)  $query = $query->order($order);
        if(false !== $fields) $query = $query->field($fields);
        $start = (intval($page['curpage'])-1)*intval($page['size']);
        $list = $query
        //->page($page['curpage'] . ',' . $page['size'])
        -> limit($start,$page['size'])
        -> select();

        if (false === $list) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        //itboye_product_attr : is_second,pid as pro_id
        //itboye_mmz_winner_pepole : uid as win_uid,goods_id
        $count = $this -> model ->alias('pro')
          -> join('left join itboye_product_attr as attr on pro.id=attr.pid')
           -> join('left join itboye_mmz_winner_pepole as wp on pro.id=wp.goods_id')
          -> where($map) -> count();

        // 分页跳转的时候保证查询条件
        // if (false !== $params) {
        //     foreach ($params as $key => $val) {
        //         $Page -> parameter[$key] = urlencode($val);
        //     }
        // }
        // $Page = new Page($count, $page['size']);
        // $show = $Page -> show();
        return $this -> apiReturnSuc(["count" => $count, "list" => $list]);
    }

    /**
     * 从商品里随机返回10个商品
     */
    public function randomQuery(){

        $count = $this->model->where(['status'=>1,'onshelf'=>Product::STATUS_ONSHELF])->count();
        if($count < 6) {
            $result = $this->model->field('id,name,price,ori_price,main_img')->where(['status'=>1,'onshelf'=>Product::STATUS_ONSHELF])->select();

        }else{
            $rand  = mt_rand(0,$count-6); //产生随机数。
            $limit = $rand.','.'6';
            $result = $this->model->field('id,name,price,ori_price,main_img')->where(['status'=>1,'onshelf'=>Product::STATUS_ONSHELF])->limit($limit)->select();
        }

        if(false === $result) return $this->apiReturnErr($this->model->getDbError());
        return $this->apiReturnSuc($result);
    }
    //二手商品详情
    public function detailGift($id,$uid){
        $fields = 'p.*,w.apply_id,m.nickname,m.head,m.sex,i.main_img';
        $result = $this->model->alias('p')
        -> join('LEFT JOIN itboye_mmz_winner_pepole as w on w.goods_id=p.id')
        -> join('(select img_id as main_img,pid from itboye_product_image where type=6015 and pid='.$id.') as i on p.id=i.pid','left')
        -> join('LEFT JOIN common_member as m on m.uid=p.uid')
        -> join('(select pid as a_id,is_second from itboye_product_attr where pid='.$id.' and is_second=1) a on a_id='.$id)
        -> join('(select id as fav_id,favorite_id  from itboye_favorites where type=1 and favorite_id='.$id.' and uid='.$uid.') f on favorite_id=p.id','left')
        -> where('`p`.`id` = '.$id)-> field($fields)->find();

        if(false === $result) return $this->apiReturnErr($this->model ->getDbError());
        return $this->apiReturnSuc($result);
    }
    //商品详情
    public function detail($id){

        $map = ['id'=>$id];
        $result = $this->model->where($map)
        ->join('(select code as origin_country,name as origin_country_name from common_datatree where parentid=35) dt on dt_origin_country = dt.origin_country','left')
        ->find();

        if(false === $result) return $this->apiReturnErr($this->model->getDbError());
        $product = $result;
        if(empty($product)) return $this->apiReturnErr('无此商品');
        // has_sku
        $has_sku = apiCall(ProductSkuApi::HAS_SKU,[$id]);
        if($has_sku['status']){
            //0为统一规格,1为多规格
            $has_sku = $has_sku['info'];
        }else{
            return $this -> apiReturnErr("商品规格信息有误!");
        }
        $product['has_sku'] = $has_sku;

        //获取商品信息
        $result = apiCall(ProductAttrApi::GET_INFO, [['pid' => $id]]);
        if (!$result['status']) return $result;

        $product_attr = $result['info'];
        if(is_null($product_attr)) return $this->apiReturnErr("商品信息有误!");

        //获取商品图片
        $main_img_type = 6015;
        $show_img_type = 6016;

        $result = apiCall(ProductImageApi::QUERY_NO_PAGING,[['pid' => $id]]);
        if(!$result['status']) return $result;

        $main_img = "";
        $img = "";
        foreach($result['info'] as $vo){
            if($vo['type'] == $main_img_type){
                $main_img = $vo['img_id'];
            }else if($vo['type'] == $show_img_type){
                $img = $img.$vo['img_id'].',';
            }
        }
        $imgs = explode(",",$img);
        array_pop($imgs);
        $product_img = [
            'main_img' => $main_img,
            'imgs'     => $imgs,
        ];
        //查询套餐信息
        
        
        /*//获取规格
        $skuItemList = [];
        $skuInfo = [];
        // if($product['has_sku']!=0){

            $map = [
                'product_id'=>$id,
            ];
            $result = apiCall(ProductSkuApi::QUERY_NO_PAGING,[$map]);

            if (!$result['status']) return $result;
            $skuItemList = $result['info'];
            $result = apiCall(SkuApi::QUERY_SKU_TABLE,[$product['cate_id']]);
            $skuInfo = $result['info'];

        // }

        $product['sku_list']      = $skuItemList;
        $product['sku_info_list'] = $skuInfo;*/
        $product = array_merge($product,$product_attr,$product_img);

        /*$result = apiCall(ProductGroupApi::GET_INFO,array(array('p_id'=>$id,'start_time'=>array('LT',time())),"price ASC"));

        $product['is_time_limit'] = 0;
        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }elseif(is_array($result['info'])){
            $product['is_time_limit'] = 1;
            $product['price'] = $result['info']['price'];
            $product['price_begin_time'] = $result['info']['start_time'];
            $product['price_end_time'] = $result['info']['end_time'];
        }
        $map  = array(
           'code' =>$product['dt_tariff_code'],
        );
        $result = apiCall(CategoryApi::GET_INFO,array(array($map)));
        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }elseif(is_array($result['info'])) {
            $product['tax_rate'] = $result['info']['taxrate'];
            $product['cate_name'] = $result['info']['name'];
        }*/

        return $this->apiReturnSuc($product);
    }


    /**
     * 查询商品包含的所有国家信息
     * @return array
     */
    public function queryAllCountry(){
        $result = $this->model->alias('p')
        ->distinct(true)
        //->field('dt_origin_country')
        ->join('left join common_datatree as dt on p.dt_origin_country = dt.code where dt.parentid=35')
        ->field('p.dt_origin_country,dt.code,dt.name')
        // ->limit(0,5)
        ->select();
        if(false === $result){
            return $this->apiReturnErr($this -> model -> getError());
        }else{
            return $this->apiReturnSuc($result);
        }
    }

    /**
     * 商品用id保存(product,product_attr,product_image)
     * @param $id
     * @param $entity
     */
    public function saveByID( $id , $entity ){
        $attr_entity = [
            'has_receipt'     => $entity['has_receipt'],
            'under_guaranty'  => $entity['under_guaranty'],
            'support_replace' => $entity['support_replace'],
            'total_sales'     => $entity['total_sales'],
            'buy_limit'       => $entity['buy_limit'],
        ];
        $img = $entity['img'];

        $properties = false;
        if(isset($entity['properties']) && count(json_decode($entity['properties'])) != 0){
            $properties = $entity['properties'];
        }

        $group = $entity['group'];

        unset($entity['id']);
        unset($entity['has_receipt']);
        unset($entity['under_guaranty']);
        unset($entity['support_replace']);
        unset($entity['total_sales']);
        unset($entity['buy_limit']);
        unset($entity['img']);

        $this->model->startTrans();//基本属性表启动事务
        $error      = false;
        $attrModel  = new ProductAttr();
        $attrModel  -> startTrans();//其他属性表启动事务
        $imageModel = new ProductImage();//M('ProductImage');
        $imageModel -> startTrans();//图片表启动事务
        $propModel  = new ProductProp();
        $propModel  -> startTrans();//prop表启动事务
        $groupModel = new ProductGroup();
        $groupModel -> startTrans();//group表启动事务

        $result = $this -> model -> where(['id' => $id]) -> save($entity);
        if($result === false){
            $error = $this -> model -> getDbError();
            return $this->apiReturnErr($error);
        }

        $result = $attrModel -> where(['pid' => $id]) -> save($attr_entity);

        if($result === false){
            $this -> model -> rollback();
            $error = $this -> model -> getDbError();
            return $this->apiReturnErr($error);
        }

        $result = $imageModel -> where(['pid' => $id]) -> delete();

        if($result === false){
            $this -> model -> rollback();
            $attrModel -> rollback();
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $create_time = time();
        $main_img_type = getDatatree('PRODUCT_MAIN_IMG');
        $show_img_type = getDatatree('PRODUCT_SHOW_IMG');
        //向图片表中插入内容
        $main_img = $img['main_img'];
        $img_list = $img['img_list'];
        $i = 0;
        if($main_img!=""){
            $img_entity[$i] = [
                'pid'         => $id,
                'img_id'      => $main_img,
                'type'        => $main_img_type,
                'create_time' => $create_time,
            ];
            $i++;
        }
        if(!is_null($img_list)) {
            foreach ($img_list as $vo) {
                $img_entity[$i] = [
                    'pid'         => $id,
                    'img_id'      => $vo,
                    'type'        => $show_img_type,
                    'create_time' => $create_time,
                ];
                $i++;
            }
        }
        if(is_array($img_entity)){
            if(count($img_entity)==1){
                $img_entity = $img_entity[0];
                $result = $imageModel -> create($img_entity,1);
                if (false === $result) {
                    $error = $imageModel -> getError();
                    $this -> model ->rollback();
                    $attrModel -> rollback();
                    $imageModel -> rollback();
                    return $this -> apiReturnErr($error);
                }
                $result = $imageModel -> add();
            }else {
                $result = $imageModel -> addAll($img_entity);
            }
        }
        if(false === $result){
            $this -> model ->rollback();
            $attrModel -> rollback();
            $imageModel -> rollback();
            $error = $imageModel -> getError();
            return $this -> apiReturnErr($error);
        }
        //像prop表中插入数据
        if(false !== $properties){
            //先删除原prop表中的属性
            $map = array(
                'pid' => $id,
            );
            $result = $propModel -> where($map) -> delete();
            if(false === $result){
                $error = $propModel -> getError();
            }
            if(false === $error){
                //删除未出错
                $properties = json_decode($properties,true);
                $data = [];
                foreach($properties as $k => $vo){
                    $map = [
                        'id' => $vo['vid'],
                    ];
                    $result = apiCall(CategoryPropvalueApi::GET_INFO,[$map]);
                    if($result['status']){
                        $prop_id = $result['info']['prop_id'];
                        $value_name = $result['info']['valuename'];
                    }else{
                        $error = $result['info'];
                        break;
                    }
                    $entity = [
                        'pid' => $id,
                        'prop_id' => $prop_id,
                        'value_id' => $vo['vid'],
                        'value_name' => $value_name,
                    ];
                    array_push($data,$entity);
                }
                if(false === $error){
                    if(is_array($data)){
                        if(count($data)==1){
                            $result = $propModel -> create($data[0],1);
                            if(false !== $result){
                                $result = $propModel -> add();
                            }else{
                                $error = $propModel -> getError();
                            }
                        }else{
                            $result = $propModel -> addAll($data);
                        }
                        if(false === $result) $error = $propModel -> getError();
                    }
                }
            }
        }
        if(false === $error){
            if($group['product_group'] !== '' && $group['product_group'] !== 0){
                $map = [
                    'p_id' => $id,
                    //'g_id' => $group['product_group'],
                ];
                $result = $groupModel -> where($map) -> delete();
                if(false === $result) $error = $groupModel -> getError();
                if(false === $error){
                    $entity = [
                        'start_time' => $group['group_start_time'],
                        'end_time'   => $group['group_end_time'],
                        'price'      => 0,
                        'p_id'       => $id,
                        'g_id'       => $group['product_group'],
                    ];
                    $result = $groupModel -> create($entity,1);
                    if(false === $result){
                        $error = $groupModel -> getError();
                    }else{
                        $result = $groupModel -> add();
                        if(false === $result) $error = $groupModel -> getError();
                    }
                }
            }
        }
        if(false === $error){
            $this -> model -> commit();
            $attrModel -> commit();
            $imageModel -> commit();
            $propModel -> commit();
            return $this -> apiReturnSuc($id);
        }else{
            $this -> model -> rollback();
            $attrModel -> rollback();
            $imageModel -> rollback();
            $propModel -> rollback();
            return $this -> apiReturnErr($error);
        }

    }

    /**
     *
     * 商品添加信息(product,product_attr,product_image)
     * @param $entity
     * @return bool|void
     */
    public function add($entity){

        $attr_entity = [
            'has_receipt'     => $entity['has_receipt'],
            'under_guaranty'  => $entity['under_guaranty'],
            'support_replace' => $entity['support_replace'],
            'total_sales'     => $entity['total_sales'],
            'buy_limit'       => $entity['buy_limit'],
        ];
        $img        = $entity['img'];//图片
        $properties = $entity['properties'];//prop属性
        $group      = $entity['group'];

        unset($entity['has_receipt']);
        unset($entity['under_guaranty']);
        unset($entity['support_replace']);
        unset($entity['total_sales']);
        unset($entity['buy_limit']);
        unset($entity['img']);
        unset($entity['properties']);

        $this->model->startTrans();//基本属性表启动事务
        $error = false;
        $attrModel = new ProductAttr();
        $attrModel -> startTrans();//其他属性表启动事务
        $imageModel = new ProductImage();
        //$imageModel = M('ProductImage');
        $imageModel -> startTrans();//图片表启动事务
        $propModel = new ProductProp();
        $propModel -> startTrans();//prop表启动事务
        $groupModel = new ProductGroup();
        $groupModel -> startTrans();//group开启事务
        $result = $this -> model -> create($entity, 1);
        $pid = 0;
        //1. 插入到商品表
        if (false === $result) {
            $error = $this -> model -> getError();
        } else {
            $result = $this -> model -> add();
            if(false === $result){
                $error = $this->model->getDbError();
            }else{
                $pid = $result;
            }
        }

        //2. 插入到商品属性表
        if(false === $error){
            $attr_entity['pid'] = $pid;
            //2. 前面没出错则插入到商品属性表
            if(false === $attrModel->create($attr_entity,1)){
                $error = $attrModel->getError();
            }else{
                $result = $attrModel->add();
                if(false === $result){
                    $error = $this->model->getDbError();
                }
            }
        }

        //3. 插入到商品图片表
        if(false === $error){
            $create_time = time();
            $main_img_type = getDatatree('PRODUCT_MAIN_IMG');
            $show_img_type = getDatatree('PRODUCT_SHOW_IMG');
            //向图片表中插入内容
            $main_img = $img['main_img'];
            $img_list = $img['img_list'];
            $i = 0;
            if($main_img!=""){
                $img_entity[$i] = [
                    'pid'         => $pid,
                    'img_id'      => $main_img,
                    'type'        => $main_img_type,
                    'create_time' => $create_time,
                ];
                $i++;
            }
            if(!is_null($img_list)){
                foreach($img_list as $vo){
                    $img_entity[$i] = [
                        'pid'         => $pid,
                        'img_id'      => $vo,
                        'type'        => $show_img_type,
                        'create_time' => $create_time,
                    ];
                    $i++;
                }
            }

            if(is_array($img_entity)){
                if(count($img_entity)==1){
                    $img_entity = $img_entity[0];
                    $result = $imageModel -> create($img_entity,1);
                    if(false === $result) $error = $imageModel -> getError();
                    $result = $imageModel -> add();
                }else{
                    $result = $imageModel -> addAll($img_entity);
                }
            }
            if(false === $result) $error = $this -> Model -> getDbError();

        }else{
            $this->model->rollback();
            return $this->apiReturnErr($error);
        }

        $properties = json_decode($properties,true);
        //4. 插入到prop表
        if($error === false && $properties != false){
            $data = [];
            foreach($properties as $k => $vo){
                $map = [
                    'id' => $vo['vid'],
                ];
                $result = apiCall(CategoryPropvalueApi::GET_INFO,[$map]);
                if($result['status']){
                    $prop_id = $result['info']['prop_id'];
                    $value_name = $result['info']['valuename'];
                }else{
                    $error = $result['info'];
                    break;
                }
                $entity = [
                    'pid'        => $pid,
                    'prop_id'    => $prop_id,
                    'value_id'   => $vo['vid'],
                    'value_name' => $value_name,
                ];
                array_push($data,$entity);
            }
            if(false === $error){
                if(is_array($data)){
                    if(1==count($data)){
                        $result = $propModel -> create($data[0],1);
                        if(false !== $result){
                            $result = $propModel -> add();
                        }else{
                            $error = $propModel -> getError();
                        }
                    }else{
                        $result = $propModel -> addAll($data);
                    }
                    if(false === $result) $error = $propModel -> getError();
                }
            }
        }

        if($group['product_group'] !== '' && $group['product_group'] !== 0){
            $map = [
                'p_id' => $pid,
                //'g_id' => $group['product_group'],
            ];
            $result = $groupModel -> where($map) -> delete();
            if(false === $result) $error = $groupModel -> getError();
            if(false === $error){
                $entity = [
                    'start_time' => $group['group_start_time'],
                    'end_time'   => $group['group_end_time'],
                    'price'      => 0,
                    'p_id'       => $pid,
                    'g_id'       => $group['product_group'],
                ];
                $result = $groupModel -> create($entity,1);
                if(false === $result){
                    $error = $groupModel -> getError();
                }else{
                    $result = $groupModel -> add();
                    if(false === $result) $error = $groupModel -> getError();
                }
            }
        }

        if($error !==false){
            $this -> model -> rollback();
            $attrModel -> rollback();
            $imageModel -> rollback();
            $propModel -> rollback();
            return $this -> apiReturnErr($error);
        }else{
            $this -> model -> commit();
            $attrModel -> commit();
            $imageModel -> commit();
            $propModel -> commit();
            return $this -> apiReturnSuc($pid);
        }


    }

    /**
     *
     * @param int $uid
     * @param null $map
     * @param array $page
     * @param bool $order
     * @param bool $params
     * @param bool $fields
     * @return array
     */
	public function queryWithStoreUID($uid=0,$map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){
		$query = $this->model;

		$result = $query->query("select * from __STORE__ where uid = $uid");

		if($result === false){
			$error = $this -> model -> getDbError();
			return $this -> apiReturnErr($error);
		}
		$storeidlist = array('0');
		foreach($result as $store){
			array_push($storeidlist,($store['id']));
		}

		$_map['storeid'] = array('in',$storeidlist);

		$map = array_merge($_map,$map);

		if(!is_null($map)){
			$query = $query->where($map);
		}

		if(!($order === false)){
			$query = $query->order($order);
		}
		if(!($fields === false)){
			$query = $query->field($fields);
		}

		$list = $query -> page($page['curpage'] . ',' . $page['size'])  -> select();


		if ($list === false) {
			$error = $this -> model -> getDbError();
			return $this -> apiReturnErr($error);
		}

		$count = $this -> model -> where($map) -> count();
		// 查询满足要求的总记录数
		$Page = new Page($count, $page['size']);

		//分页跳转的时候保证查询条件
		if ($params !== false) {
			foreach ($params as $key => $val) {
				$Page -> parameter[$key] = urlencode($val);
			}
		}

		// 实例化分页类 传入总记录数和每页显示的记录数
		$show = $Page -> show();

		return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
	}

    /**
     * @param $name
     * @param $type
     * @param $page
     * @param $order
     * @param $params
     * @return array
     */
    public function queryWithStore($name,$type,$page,$order,$params){


        $query = $this->model;//->field("")->alias(" pd ")->join("LEFT JOIN __WXSTORE__ as st on st.id = pd.storeid ");

        $sql = "select  pd.name as name ,pd.id,pd.main_img,pd.buy_limit,pd.attrext_ispostfree,pd.attrext_ishasreceipt,pd.attrext_issupportreplace,pd.loc_country,pd.loc_province,pd.loc_city,pd.loc_address,pd.has_sku,pd.ori_price,pd.price,pd.quantity,pd.product_code,pd.cate_id,
		pd.createtime,pd.updatetime,pd.onshelf,pd.status,pd.storeid,pd.properties,pd.sku_info,pd.detail,st.uid,st.name as storename,st.desc,st.isopen,st.logo,st.banner,st.wxno,st.exp";
        $sql .= " from __PRODUCT__ as pd LEFT JOIN __STORE__ as st on st.id = pd.storeid  ";
        if($type == '1'){
            $whereName = " pd.name ";
        }else{
            $whereName = "st.name";
        }
        $sql .= " where pd.onshelf = ".Product::STATUS_ONSHELF;
        if(!empty($name)){
            $sql .= " and  $whereName like '%".$name."%' ";
        }

        $sql .= ' order by '. $order;
//		if(!($order === false)){
//			$query = $query->order($order);
//		}
        $sql .= " LIMIT ".(intval($page['curpage'])*$page['size']) . ',' . $page['size'];

        $list = $query->query($sql);


        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        $countSql = " select count(*) as cnt from __PRODUCT__ as pd LEFT JOIN __STORE__ as st on st.id = pd.storeid   ";
        if(!empty($name)){
            $countSql .= " where $whereName like '%".$name."%'";
        }

        $count = $query->query($countSql);
        $count = $count[0]['cnt'];
        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        // 分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));

    }

    /**
     * 商品分组分页查询
     * @param $group_id
     * @param $map
     * @param $page
     * @return array
     */
    public function queryByGroup($group_id,$map,$page){
        $result = $this->model->query("select g_id,p_id from __PRODUCT_GROUP__ where `g_id` = ".$group_id);
        if(false === $result) return $this->apiReturnErr($this->model->getDbError());
        $product_ids = [-1];

        foreach($result as $vo){
            array_push($product_ids,$vo['p_id']);
        }

        if(empty($map))  $map = [];
        $map['id']      = ['in',$product_ids];
        $map['status']  = 1;
        $map['onshelf'] = Product::STATUS_ONSHELF;

        $query = $this->model;
        if(!empty($map)) $query = $query->where($map);
        if(false !== $order) $query = $query->order($order);
        if(false !== $fields) $query = $query->field($fields);
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();


        if (false === $list){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        // 分页跳转的时候保证查询条件
        if (false !== $params) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();
        return $this -> apiReturnSuc(["show" => $show, "list" => $list]);

    }

}